import { ref, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import * as authApi from '@/api/auth'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

export function useAuth() {
  const userStore = useUserStore()
  const router = useRouter()
  
  const loading = ref(false)
  const loginForm = ref({
    username: '',
    password: '',
    remember: false
  })

  // 计算属性
  const isLoggedIn = computed(() => userStore.isLoggedIn)
  const userInfo = computed(() => userStore.userInfo)
  const permissions = computed(() => userStore.permissions)
  const roles = computed(() => userStore.roles)

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      const result = await userStore.login(credentials)
      if (result.success) {
        ElMessage.success('登录成功')
        
        // 记住密码
        if (credentials.remember) {
          localStorage.setItem('rememberedUsername', credentials.username)
        } else {
          localStorage.removeItem('rememberedUsername')
        }
        
        // 跳转到首页或之前访问的页面
        const redirect = router.currentRoute.value.query.redirect || '/dashboard'
        router.push(redirect)
        
        return { success: true }
      } else {
        ElMessage.error(result.message || '登录失败')
        return { success: false, message: result.message }
      }
    } catch (error) {
      const message = error.message || '登录失败，请稍后重试'
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('Logout API error:', error)
    }
    
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  }

  // 注册
  const register = async (userData) => {
    loading.value = true
    try {
      const response = await authApi.register(userData)
      ElMessage.success('注册成功，请登录')
      return { success: true, data: response }
    } catch (error) {
      const message = error.message || '注册失败'
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    loading.value = true
    try {
      await authApi.changePassword(passwordData)
      ElMessage.success('密码修改成功')
      return { success: true }
    } catch (error) {
      const message = error.message || '密码修改失败'
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 重置密码
  const resetPassword = async (resetData) => {
    loading.value = true
    try {
      await authApi.resetPassword(resetData)
      ElMessage.success('密码重置成功')
      return { success: true }
    } catch (error) {
      const message = error.message || '密码重置失败'
      ElMessage.error(message)
      return { success: false, message }
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const userInfo = await authApi.getUserInfo()
      userStore.setUserInfo(userInfo)
      return userInfo
    } catch (error) {
      console.error('Failed to fetch user info:', error)
      throw error
    }
  }

  // 检查权限
  const hasPermission = (permission) => {
    return userStore.hasPermission(permission)
  }

  // 检查角色
  const hasRole = (role) => {
    return userStore.hasRole(role)
  }

  // 检查多个权限
  const hasAnyPermission = (permissions) => {
    return permissions.some(permission => hasPermission(permission))
  }

  // 检查多个角色
  const hasAnyRole = (roles) => {
    return roles.some(role => hasRole(role))
  }

  // 初始化认证状态
  const initAuth = async () => {
    userStore.initFromStorage()
    
    if (userStore.token) {
      try {
        await fetchUserInfo()
      } catch (error) {
        // Token可能已过期，清除本地状态
        userStore.logout()
      }
    }
  }

  // 获取记住的用户名
  const getRememberedUsername = () => {
    return localStorage.getItem('rememberedUsername') || ''
  }

  return {
    // 状态
    loading,
    loginForm,
    
    // 计算属性
    isLoggedIn,
    userInfo,
    permissions,
    roles,
    
    // 方法
    login,
    logout,
    register,
    changePassword,
    resetPassword,
    fetchUserInfo,
    hasPermission,
    hasRole,
    hasAnyPermission,
    hasAnyRole,
    initAuth,
    getRememberedUsername
  }
}
